import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {Router, ActivatedRoute} from "@angular/router";
import {MsgChannelService} from "./msgChannel.service";
import {ResponseUtil} from "../../../../util/response-util";
import {MsgResult} from "../../../../models/msg-result";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../../util/page-subject";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {OneOperationComponent} from "../../../../widgets/one-operation/one-operation.component";
import {TableUtil} from "../../../../util/table-util";
import {MsgConstants} from "../../../../constants/constants";
import {MsgAPI} from '../../msg-constants';

declare var $;
declare var moment;
declare var datepicker;

@Component({
  selector: 'app-channel',
  templateUrl: './channel.component.html',
  styleUrls: ['./channel.component.css']
})
export class ChannelComponent implements OnInit, AfterViewInit {

  @ViewChild(OneOperationComponent) operation: OneOperationComponent;
  //存储初始化表单数据

  id: Array<string> = [];

  table;

  constructor(private route: Router,
              private router: ActivatedRoute,
              private channelService: MsgChannelService,
              private pageSubject: PageSubject,
              private tableUtil: TableUtil,
              private dialogService: OneDialogService,
              private response: ResponseUtil) {
  }

  proxy = {
    "channelAdd": () => this.channelAdd(),
    "channelUpdate": () => this.channelUpdate(),
    "channelDelete": () => this.channelDelete(),
    "channelAssign":() =>this.channelAssign()
  }

  ngOnInit() {
    this.pushPage();
    this.loadChannels();
  }

  ngAfterViewInit() {
    //操作函数代理
    this.operation.proxy = this.proxy;
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    let path = new Path("报警管理", "");
    this.pageSubject.pushPage("报警通道管理", "查询", path);
  }

  /**
   * 添加页面跳转
   */
  channelAdd() {
    this.route.navigate(['add'], {relativeTo: this.router});
  }

  /**
   * 分配发送人
   */
  channelAssign(){

    let rows = this.table.bootstrapTable('getSelections');
    this.id = this.tableUtil.getCloumns(rows, "id");
    if (this.id.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.route.navigate(['assign-receiver'], {relativeTo: this.router});
    }
  }

  /**
   * 实现删除弹窗
   */
  channelDelete() {
    let rows = this.table.bootstrapTable('getSelections');
    this.id = this.tableUtil.getCloumns(rows, "id");
    if (undefined == this.id || 0 == this.id.length) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.dialogService.modalInfoWithCancelBtn("确定删除？", this.requestDelete);
    }

  }

  /**
   * 实现删除操作
   * 1.调取后端删除操作；
   */
  private requestDelete = () => {
    //调用后端接口
    if (this.id.length == 1) {
      this.channelService.deleteChannel(this.id[0]).subscribe(
        result => this.response.success(result, this.processDeleteResult),
        message => this.response.error(message)
      );
    } else {
      this.channelService.deleteChannels(this.id).subscribe(
        result => this.response.success(result, this.processDeleteResult),
        message => this.response.error(message)
      );
    }
  }
  private processDeleteResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message);
      this.search();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  search() {
    this.table.bootstrapTable('refresh');
  }

  /**
   * 修改页面跳转传参
   */
  channelUpdate() {
    let rows = this.table.bootstrapTable('getSelections');
    this.id = this.tableUtil.getCloumns(rows, "id");
    if (this.id.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.route.navigate(['update', {id: this.id[0]}], {relativeTo: this.router});
    }
  }

  /**
   * 通道查询
   */
  loadChannels() {
    this.table = this.tableUtil.load("one_table_channel", {
      columns: [
        {checkbox: true},
        {field: "id", title: 'ID', align: 'left', visible: false, switchable: false},
        {field: "alarmName", title: '报警通道名', align: 'left', switchable: false},
        {field: "type", title: '类型', align: 'left', formatter: this.typeFormat},
        {field: "sendMode", title: '发送方式', align: 'left', formatter: this.sendModeFormat},
        {field: "level", title: '发送级别', align: 'left', formatter: this.levelFormat},
        {field: "receiverName", title: '发送对象', align: 'left', formatter : this.stringFormat},
        {field: "isReal", title: '是否实时', align: 'left', formatter: this.yesOrNoFormat},
        {field: "startTime", title: '开始时间', align: 'left'},
        {field: "endTime", title: '结束时间', align: 'left'},
        {field: "isUse", title: '有效', align: 'left', formatter: this.yesOrNoFormat},
        {field: "creatorName", title: '创建人', align: 'left'},
        {field: "create_date", title: '创建日期', align: 'left', sortName: "CREATE_DATE", sortable: true},
        {field: "updatorName", title: '修改人', align: 'left', visible: false},
        {field: "update_date", title: '修改日期', align: 'left', sortName: "UPDATE_DATE", sortable: true, visible: false}
      ],
      idField: "id",
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10, 15, 50],
      paginationPreText: "上一页",
      paginationNextText: "下一页",
      paginationLoop: false,//是否开启循环分页
      singleSelect: false,//多选
      clickToSelect: true,//点击选中
      toolbar: "#one_operation_channel",
      url: MsgAPI.channelsPageListV2,
      method: 'post',
      //传递附加参数
      queryParams: (params) => {
        params.alarmName = $("#channelName").val();
        return params;
      },
      //返回数据处理器
      responseHandler: (result) => {
        return this.response.bsPageHandler(result, (result) => {
          result.data.rows.forEach(function (value) {
            value.create_date = value.createDate || '';
            value.update_date = value.updateDate || '';
          });
        });
      },
      height: 700,//table高度
      sortable: true,
      sortOrder: 'desc',
      sortName: 'CREATE_DATE',
      showColumns: true,//显示自定义显示列按钮
      showRefresh: true,//显示刷新按钮
      minimumCountColumns: 3,//最少保留显示的列数量
      showToggle: true,//显示视图切换按钮
      showPaginationSwitch: true,//显示是否分页切换按钮
      classes: "table table-hover",
      striped: true,//隔行变色
      mobileResponsive: true//响应式
    });
  }

  /**
   * 字符超过40后，只显示40个字
   * @param value
   * @param row
   * @param index
   * @returns {string}
   */

  private stringFormat(value, row, index) {

    if(!value){
      return '-';
    }
    //
    // if (value.length > 40) {
    //   return value.substring(0, 40)+"...";
    // }
    // return value;
    return '<span style="display: inline-block;width: 180px;" title="'+value+'">'+value+'</span>'
  }

  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private yesOrNoFormat(value, row, index) {
    if (value == '1') {
      return '是';
    }
    if (value == '0') {
      return '否';
    }
  }

  /**
   * 发送方式判断
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */

  private sendModeFormat(value, row, index) {
    if (value == '1') {
      return '应用内';
    }
    if (value == '2') {
      return '短信';
    }
    if (value == '3') {
      return '邮件';
    }
  }

  /**
   * 报警级别判断
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */

  private levelFormat(value, row, index) {
    switch (value){
      case '1':
        return '蓝色';
      case '2':
        return '黄色';
      case '3':
        return '橙色';
      case '4':
        return '红色';
      default:
          return '-';
    }
  }

  /**
   * 报警类型判断
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */

  private typeFormat(value, row, index) {
    if (value == '1') {
      return '标准站';
    }
    if (value == '2') {
      return '微型站';
    }
    if (value == '3') {
      return '工业废气';
    }
    if (value == '4') {
      return '扬尘';
    }
    if (value == '5') {
      return '油烟';
    }
    if (value == '6') {
      return '油漆房';
    }
    if (value == '7') {
      return '加油站';
    }
    if (value == '8') {
      return '工业废水';
    }
    if (value == '9') {
      return '水质断层';
    }
    return '其他';

  }

}
